$(document).ready(function () {
    var value = 0;
    var time = 850;

    $('#start').click(function () {
        var sent = $('#sent').val();
        if (sent == "" || sent == " ") {
            alert('请输入句子');
        }


        $.ajax({
            url: "http://127.0.0.1:3010/back/articles/showArticles",
            type: "get",
            dataType: "json",
            timeout : 600000,
            // dataType: "text",
            data: JSON.stringify({data:sent}),
            async:true,
            beforeSend: function () {
                $('#start').button('loading');
                $('#btn_start').after(get_pgbar());
                increment();
            },
            success: function (data) {
                console.log(data);
                console.log('数据返回完成')
                value = 100;
                reset();
                $('#start').button('reset');
                $('#pgbar').remove();
                $('#result').empty();
                sent = data[data.length - 1].sent;
                var tokens = '';
                sent.forEach(function (value) {
                    tokens += value + " "
                });

                for (var i = 0; i < data.length - 1; i++) {
                    $('#result').append(get_event_type(data[i]['event-type']));
                    $('#result').append(span_tri(data[i].tri, sent));
                    tokens = tokens.replace(sent[data[i].tri], '<label class="bg-success">'+sent[data[i].tri]+'</label>')

                    span_args(data[i].ent, sent).forEach(function (value) {
                        $('#result').append(value)
                    });

                    $('#result').append(get_divider());
                }

                $('#result').prepend("<p><span class='glyphicon glyphicon-list-alt left'></span>" + tokens + "</p>");

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //TODO: 处理status， http status code，超时 408
                // 注意：如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能
                console.log('time out');
                console.log(textStatus);
                $('#start').button('reset');
                console.log('出错 value='+value);
                $('#pgbar').remove();
            },
            complete: function () {
                $('#start').button('reset');
                $('#pgbar').remove();
            }
        });
    });


    function reset() {
        value = 0;
        $("#prog").removeClass("progress-bar-success").css("width","0%").text("等待启动");

    }

    function increment() {
        if (value < 99) {
            value += 1;
            $("#prog").css("width",value + "%").text(value + "%");
            if (value>=0 && value<=30) {
                $("#prog").addClass("progress-bar-danger");
            }
            else if (value>=30 && value <=60) {
                $("#prog").removeClass("progress-bar-danger");
                $("#prog").addClass("progress-bar-warning");
            }
            else if (value>=60 && value <=90) {
                $("#prog").removeClass("progress-bar-warning");
                $("#prog").addClass("progress-bar-info");
            }
            else if(value >= 90 && value<100) {
                $("#prog").removeClass("progress-bar-info");
                $("#prog").addClass("progress-bar-success");
            }
        }
        else if (value = 100){
            console.log('value=100');
            setTimeout(reset, time);
            return;
        }
        st = setTimeout(increment,time);
    }
})

function span_tri(tri_index, sent) {
    var tri_span = "<div class='tri'><label><span class='glyphicon glyphicon-triangle-right'></span>触发词: </label><span class='tri'>" + sent[tri_index] + "</span></div>"

    console.log(tri_span);
    return tri_span;
}

function span_args(ent, sent) {
    var index_arr = Object.keys(ent);
    console.log(index_arr)
    var span_args = '';
    var ent_arr = Array();
    for(var i=0; i<index_arr.length; i++) {
        if (ent[index_arr[i]] === 't') {
            span_args = '<span class="glyphicon glyphicon-time econ">时间：</span><span class="ent">'+sent[index_arr[i]]+'</span>'
        } else if (ent[index_arr[i]] === 'o') {
            span_args = '<span class="glyphicon glyphicon-user econ">客体：</span><span class="ent">'+sent[index_arr[i]]+'</span>'
        } else if (ent[index_arr[i]] === 'l') {
            span_args = '<span class="glyphicon glyphicon-map-marker econ">地点：</span><span class="ent">'+sent[index_arr[i]]+'</span>'
        } else  if (ent[index_arr[i]] === 'None') {
            continue
        } else
            span_args = '<span class="glyphicon glyphicon-user econ">主体：</span><span class="ent">'+sent[index_arr[i]]+'</span>'

        ent_arr.push(span_args)
    }
    console.log(ent_arr)
    return ent_arr;
}

function get_event_type(event_type) {
    var event = ['None', 'thoughtevent', 'emergency', 'movement', 'statement', 'operation', 'stateChange', 'perception', 'action'];
    return '<p style="padding-top: 10px"><label>事件类型：</label><span>'+event[event_type]+'</span></p>'
}

function get_divider() {
    return '<div class="bg-primary divider mtop" style="height: 5px"></div>'
}

function get_pgbar() {
    return '  <div class="progress progress-striped active mtop" id="pgbar">\n' +
        '            <div id="prog" class="progress-bar" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" style="width:0%;">\n' +
        '                <span id="proglabel">正在启动，请稍后......</span>\n' +
        '            </div>\n' +
        '        </div>'
}
